<?php

use App\Models\Markdown;
use App\Models\QRCode;
use App\Models\FingerPrint;
use Illuminate\Http\Request;
use Illuminate\Http\File;

function uuid() {
    $uuid = '';
    if (!function_exists('uuid_create')){
        $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        // 16 bits for "time_mid"
        mt_rand(0, 0xffff),
        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand(0, 0x0fff) | 0x4000,
        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand(0, 0x3fff) | 0x8000,
        // 48 bits for "node"
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
      );
    }
    else{
        $uuid = uuid_create();
    }
    $uuid = str_replace('-', '', strtolower($uuid));
    return $uuid;
}

if(!empty($_COOKIE['debug'])){
    config(['app.debug' => true]);
}


function debug($value){
  if(config('app.debug')){
    if(request()->ajax()){
        var_dump($value);
    }
    else{
      dump($value);
    }
  }
}
function ddd($value){
  if(config('app.debug')){
    if(request()->ajax()){
        var_dump($value);
        die(1);
    }
    else{
      dd($value);
    }
  }
}

function markdown($text){
    try{
        $parsedown = new Markdown();
        $content = $parsedown->text($text);
    }
    catch(\Exception $ex){
        $content = $text;
    }
  return $content;
}

function qrcode($args){
    $argList = func_get_args();
    if(func_num_args() == 1){
        $id = $argList[0];
        $id = strtr($id, ['../'=>'', './'=>'']);
        return url('qr/' . $id . '.jpg');
    }
    else{
        $qrcode = new QRCode();
        $qrcode->content = empty($argList[0])?'':$argList[0];
        $qrcode->expiredAt = empty($argList[1])?0:$argList[1];
        $id = $qrcode->add();
        return $id;
    }
}

function identity(){
  $identity = FingerPrint::identity();
  return $identity;
}

function agent(){
    $request = request();
    $agent = $request->server('HTTP_USER_AGENT', '') . ' ' . $request->server('HTTP_Q_UA', '');
    return $agent;
}

function outputCsv($data, $filename, $emptyString = 'No Data'){
    if($data==false || count($data)==0){
        echo $emptyString;
        exit;
    }

    header('Content-Type: text/csv; charset=UTF-8');
    header("Content-Disposition: attachment; filename={$filename}.csv");
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header('Pragma:public');

    ob_start();
    $fp = fopen( 'php://output', 'w' ) or die();

    fputcsv($fp, array_keys(reset($data)));
    foreach ($data as $dataRow){
        fputcsv($fp, array_values($dataRow));
    }

    @fclose($fp);
    $output = ob_get_contents();
    ob_end_clean();
    echo "\xEF\xBB\xBF" . $output;
    exit;
}


function curlGet($url, $options = array(), $srcEncoding = 'UTF-8', $tarEncoding='UTF-8', $timeoutSecond = null){
    $curl = curl_init($url);
    $defaultOptions = array(
        CURLOPT_RETURNTRANSFER => true,
    );
    if(!is_null($timeoutSecond)){
        $defaultOptions[CURLOPT_TIMEOUT] = $timeoutSecond;
    }
    $options = $defaultOptions + $options;
    curl_setopt_array ($curl, $options);
    $res = curl_exec($curl);
    $info = curl_getinfo($curl);
    curl_close($curl);
    if($srcEncoding != $tarEncoding){
        $res = iconv($srcEncoding, $tarEncoding, $res);
    }
    
    return [
        'info' => $info,
        'content' => $res,
    ];
}

function curlPost($url, $data = array(), $options = array(), $srcEncoding = 'UTF-8', $tarEncoding='UTF-8', $timeoutSecond = null){
    $curl = curl_init($url);
    $defaultOptions = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data,
    );
    if(!is_null($timeoutSecond)){
        $defaultOptions[CURLOPT_TIMEOUT] = $timeoutSecond;
    }
    $options = $defaultOptions + $options;
    curl_setopt_array ($curl, $options);
    $res = curl_exec($curl);
    $info = curl_getinfo($curl);
    curl_close($curl);
    if($srcEncoding != $tarEncoding){
        $res = iconv($srcEncoding, $tarEncoding, $res);
    }
    
    return [
        'info' => $info,
        'content' => $res,
    ];
}

function isMobile(){
 //正则表达式,批配不同手机浏览器UA关键词。
 $regex_match="/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|";
 $regex_match.="htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|";
 $regex_match.="blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|";
 $regex_match.="symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|";
 $regex_match.="jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220";
 $regex_match.=")/i";

 return isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']) or preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT'])); //如果UA中存在上面的关键词则返回真。
}

function redirectTo($url, $waitSeconds = 0){
    header('HTTP/1.1 302 Moved Temporarily');
    if($waitSeconds == 0){
        header("Location: {$url}");
        exit;
    }
    else{
        header("Refresh: {$waitSeconds};url={$url}");
    }
}

function static_asset($path = ''){
    $staticServiceUrl = env('STATIC_FILE_HOSTING');
    return "{$staticServiceUrl}/$path";
}

function readCsv($filename){
    ini_set("auto_detect_line_endings", true);
    $rows = [];
    if ($csvFileHandler = fopen($filename, 'r')) {
        $columns = fgetcsv($csvFileHandler, 0, ",");
        while (($rowData = fgetcsv($csvFileHandler, 0, ",")) !== false) {
            foreach ($columns as $columnIndex => $columnName) {
                if(empty($columnName)) continue;
                $row[$columnName] = $rowData[$columnIndex];
            }
            $rows[] = $row;
        }
    }
    return $rows;
}
